<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { uploadApiNew } from '#/api/core/upload';
import { userAdd, userUpdate } from '#/api/system/user';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const avatar = ref<string>('');
const handleUpload = (file: File) => {
  console.log('file :>>', file);
  uploadApiNew({
    file,
    onSuccess: (data) => {
      avatar.value = data.objectName;
    },
  });
};
const handleRemove = () => {
  avatar.value = '';
};
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(handleUpload, handleRemove),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id, avatar: avatarValue, ...rest } = modalApi.getData();
    isUpdate.value = !!id;
    const objectName = avatarValue?.split('/').pop();
    avatar.value = objectName || '';

    if (isUpdate.value && id) {
      await formApi.setValues({
        ...rest,
        id,
        avatar: avatarValue
          ? [{ uid: '-1', name: objectName, status: 'done', url: avatarValue }]
          : undefined,
      });
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    const data = cloneDeep(await formApi.getValues());

    // 新增时验证密码
    if (isUpdate.value) {
      // 编辑时传userId而不是id
      data.userId = data.id;
      delete data.id;
      delete data.password;
      delete data.confirmPassword;
    } else {
      if (data.password !== data.confirmPassword) {
        throw new Error('两次输入的密码不一致');
      }
    }
    data.avatar = avatar.value;
    await (isUpdate.value ? userUpdate(data) : userAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[550px]">
    <BasicForm />
  </BasicModal>
</template>
